package br.com.salao.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JpaUtil {
	
	static EntityManager em;
	private static EntityManagerFactory emf;
	public static String persistenceUnitName = "Salao";


	public static EntityManagerFactory getEntityManagerFactory(String persistenceUnitName) {
		if(emf == null){
			emf = Persistence.createEntityManagerFactory(persistenceUnitName);
		}
		return emf;
	}
	/**
	 * Retorna um  Entity manager para a Persistence unit passada
	 * @param persistenceUnitName
	 * @return
	 */
	public static EntityManager getEntityManager(String persistenceUnitName) { 		
		em = getEntityManagerFactory(persistenceUnitName).createEntityManager();		
		closeEntityMgrFactory();		
		return em;
	}
	
	//Para Testar
	public static EntityManager getEntityManager() { 		
		em = getEntityManagerFactory(persistenceUnitName).createEntityManager();		
		closeEntityMgrFactory();		
		return em;
	}
	
	public static void closeEntityMgrFactory(){
		if(emf != null){
			emf.close();
		}		
	}
}